const app = getApp();
const { htmlEncode, checkInputCode} = require('../../utils/util.js')
import {ILLEGALTYPEARRAY} from "../../public/utils/const.js";
const api = app.apiInstance;

import {
  getUserInfo,
  setUserInfo
} from "../../utils/store"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,
    tempFilePaths: '',
    illegalTypeArray: ILLEGALTYPEARRAY,
    selfDeptArray:['否','是'],
    illegalTypeIndex: null,

    imgList: [],
    deptList: [],
    personnelAreaList: [],
    areaIndex:'',
    location: null,
    content: null,
    suggest: null,
    selfDept:'',
    selfDeptIndex:'',
    bigSearchShow: false,
    bigSearchType: "",
    saferFlag: null,
    dept: "",
    searchDataList: [],
    imgSuccessLoaded:[],
    isYingJiBu:false,
    userInfo:getUserInfo(),
    personnelArea:'',

    isQuYu:false,
  },
  getAllDept: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/deptInfo/wx/getAllDept',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取所有部门信息:', res.data);
        var data = res.data;
        that.setData({
          deptList: data.data
        })
      }
    });
  },
  riskLevelChange: function (e) {
    console.log('隐患分级选择变化，携带值为', e.detail.value)
    this.setData({
      riskLevelIndex: e.detail.value
    })
  },
  init: function () {
    this.getAllDept();
    if (this.data.userInfo.siocDepartCode == '应急管理部') {
      this.setData({
        isYingJiBu:true
      })
      
    }

    if (this.data.userInfo.siocDepartCode == '生产部') {
      this.setData({
        isQuYu:true,
        personnelAreaList:["PM11纸机区域","PM12纸机区域","PM13纸机区域"]
      })
    }
    if (this.data.userInfo.siocDepartCode == '无纺布生产部') {
      this.setData({
        isQuYu:true,
        personnelAreaList:["无纺一期","无纺二期"]
      })
    }

   
  },


  illegalTypeChange: function (e) {
    this.setData({
      illegalTypeIndex: e.detail.value
    })
  },

  selfDeptChange: function (e) {
    this.setData({
      selfDeptIndex: e.detail.value,
      selfDept: e.detail.value
    })
  },

  personnelAreaChange: function (e) {
    this.setData({
      personnelAreaIndex: e.detail.value,
      personnelArea: this.data.personnelAreaList[e.detail.value]
    })
  },

  
  
  
  submitForm(e) {
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    var that = this;
    const formData = e.detail.value;
   
    formData.imgList = that.data.imgList;
    formData.dept = that.data.dept;
    formData.personnelArea = that.data.personnelArea
    console.log('form发生了submit事件，携带数据为：', formData);

    var errMsg = "";
    if (!formData.selfDept&&!that.data.isYingJiBu) {
      errMsg = errMsg + "是否部门内部不能为空;";
    }
    
    if (!formData.location) {
      errMsg = errMsg + "具体位置不能为空;";
    }
    if (formData.imgList.length < 1) {
      errMsg = errMsg + "违规图片或者视频不能为空;";
    }
    if (!formData.content) {
      errMsg = errMsg + "违规内容不能为空;";
    }
    if(!formData.dept&&that.data.isYingJiBu){
      errMsg = errMsg + "部门不能为空;";
    }

    if (!formData.illegalType) {
      errMsg = errMsg + "违规类型不能为空;";
    }
  
    if(checkInputCode(formData.location)){
      errMsg = errMsg + "位置不允许输入特殊字符;";
    }

    if(checkInputCode(formData.content)){
      errMsg = errMsg + "问题情况不允许输入特殊字符;";
    }


    // for(let i in formData){
    //   formData[i] = htmlEncode(formData[i])
    // }
    if(that.data.imgSuccessLoaded.length>0 && that.data.imgSuccessLoaded.filter(item=>item==0).length>0){
      errMsg = errMsg + "请检查是否上传正确的图片;";
    }
    // if (!formData.riskLevel) {
    //   errMsg = errMsg + "隐患分级不能为空;";
    // }



    console.log('form发生了submit事件，携带数据为：', formData);
    if (errMsg.length > 0) {
      wx.hideLoading()
      wx.showModal({
        title: '提示',
        content: errMsg,
        showCancel: false
      })
      return;
    }

    // 向服务器提交表单数据

    api.post('/illegalRecord/wx/addBill',formData).then(res=>{
      if (200 == res.code) {


        wx.navigateTo({
          url: '/pages/illegal-list/illegal-list'
        })


        // that.setData({
        //   tempFilePaths: '',
        //   location: null,
        //   content: null,
        //   illegalType: '',
        //   illegalTypeIndex: null,
 
       
        // });
      }
    })

    
  },
  ViewImage(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    for (let key in this.data.imgList) {
      urls.push(this.data.fileUrl + this.data.imgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  DelImg(e) {



    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.data.imgSuccessLoaded.splice(e.currentTarget.dataset.index, 1);
          
          this.setData({
            imgList: this.data.imgList,
            imgSuccessLoaded:this.data.imgSuccessLoaded
          })
        }
      }
    })
  },


  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      async success(res) { // 将图片上传到服务器

        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.imgList.length != 0) {
              that.setData({
                imgList: that.data.imgList.concat(tempArray)
              })
            } else {
              that.setData({
                imgList: tempArray
              })
            }
          }
        })
      }
    })
  },

  imageLoad(e){
    

    this.data.imgSuccessLoaded.push(1)
    this.setData({
      imgSuccessLoaded:this.data.imgSuccessLoaded
    })


  },

  imageError(e){

    this.data.imgSuccessLoaded.push(0)
    this.setData({
      imgSuccessLoaded:this.data.imgSuccessLoaded
    })
  },

  doBigSearchShow(e) {
    console.log('e', e);
    const tempArray = [];
    const typeMethods = {
      dept: () => {
        if (this.data.deptList.length == 0) {
          wx.showToast({
            title: '暂无部门指派',
            icon: 'none'
          });
          return;
        } else {
          this.data.deptList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      }
    }
    typeMethods[e.currentTarget.dataset.type]();

    this.setData({
      bigSearchType: e.currentTarget.dataset.type,
      bigSearchShow: true,
      searchDataList: tempArray
    })
  },
  searchSelect(e) {
    
    this.setData({
      dept:e.detail.name
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.init();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})